package com.bieyang.anjia.ui.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.bieyang.anjia.R;
import com.bieyang.anjia.module.Device;
import com.bieyang.anjia.net.NetManager;
import com.bieyang.anjia.utils.Constants;
import com.bieyang.anjia.utils.Show;
import com.bieyang.anjia.utils.ShowProgress;
import com.bieyang.anjia.utils.SubUtils;

@SuppressLint("HandlerLeak")
public class UpdateDiviceNameActivity extends BaseNomalActivity {
	private EditText nameEdit;
	Context con;
	NetManager netManager = new NetManager();
	ShowProgress progressDialog;
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case Constants.UPDATE_SUBNAME_SUCCESS:
				progressDialog.dismiss();
				Intent intent = new Intent();
				intent.putExtra(Constants.DIVICE_NAME, nameEdit.getText()
						.toString());
				setResult(2004, intent);
				finish();
				break;
			case Constants.UPDATE_SUBNAME_FAILED:
				progressDialog.dismiss();
				Show.toast(con, R.string.save_name_fail);
				break;
			default:
				break;
			}
		};
	};

	@Override
	void setContent() {
		con = this;
		setContentView(R.layout.update_divice_name);
	}

	@Override
	void initView() {
		Button save = (Button) findViewById(R.id.save_name);

		save.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				Log.d("update", "save");
				saveName();
			}
		});
		TextView titleName = (TextView) findViewById(R.id.topLineTitle);
		titleName.setText(getString(R.string.update_divice_name));
		nameEdit = (EditText) findViewById(R.id.update_name_edit);
	}

	@Override
	void initData() {
		nameEdit.setHint(name);
	}

	@Override
	void setListener() {

	}

	@Override
	protected void saveStatus() {
		super.saveStatus();
		finish();
	}

	/**
	 * 保存名称
	 */
	protected void saveName() {
		String name = nameEdit.getText().toString();
		if (App.isLogin) {
			if (NetManager.subOnLineMap.get(uuid).toString().equals("ONLINE")) {
				if (null != id && null != name && !name.isEmpty()) {
					if (null == progressDialog) {
						progressDialog = SubUtils.showProgress(con);
					} else {
						progressDialog.show();
					}
					Log.d("updateName", "id=" + id + "---name=" + name);
					Device device = new Device();
					device.setDiviceId(id);
					device.setDiviceName(name);
					netManager.updateSubName(device, mHandler);
				} else {
					Show.toast(con, R.string.name_err);
				}
			} else {
				Show.toast(con, R.string.sub_off_line);
			}
		} else {
			Show.toast(con, R.string.please_login);
		}
	}
}
